<?php
namespace app\index\logic;

use think\facade\Db;
use think\facade\Session;

class Token
{
    public static function token($code)
    {
        $appid = APPID;
        $appsecret = APPSECRET;
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
        $rt = json_decode(https_request($url),true);
        $user = Db::name('user')->where('openid','=',$rt['openid'])->find();
        if ($user==null){
            $url3 = "https://api.weixin.qq.com/sns/userinfo?access_token={$rt['access_token']}&openid={$rt['openid']}&lang=zh_CN";
            $rt3 = json_decode(https_request($url3),true);
            $data = [
                'nickname'=>$rt3['nickname'],
                'openid'=>$rt3['openid'],
                'head_img'=>$rt3['headimgurl'],
                'addtime'=>time(),
                'sex'=>$rt3['sex'],
            ];
            $add = Db::name("user")->insertGetId($data);
            Session::set('user',$add);
        }else{
            Session::set('user',$user['id']);
        }
    }

}